﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.Xml;
using System.IO;

namespace Mdv.wssAddins
{
    public partial class XmlEditorForm : Form
    {
        private XmlNode _value;
        public XmlNode Value
        {
            get { return _value; }
            set { _value = value; }
        }
        IWindowsFormsEditorService editorService = null;
        public XmlEditorForm(IWindowsFormsEditorService editorService)
        {
            this.editorService = editorService;
            InitializeComponent();
        }
        public XmlEditorForm()
        {
            InitializeComponent();
        }
        private void XmlEditorForm_Load(object sender, EventArgs e)
        {
            rtbXML.Text = FormatXML(Value);
        }
        public string FormatXML(XmlNode node)
        {
            using (StringWriter sw = new StringWriter())
                using (XmlTextWriter xtw = new XmlTextWriter(sw))
                {
                    xtw.Formatting = System.Xml.Formatting.Indented;
                    //xtw.Namespaces = false;
                    //xtw.WriteRaw(node.InnerXml);
                    //if I WriteContentTo, xmlns will be added to the string. tehrfore, I write the whole node and use regex to strinp the enclosing tags
                    node.WriteTo(xtw);
                    string s = sw.ToString();
                    Regex rgHtml = new Regex(@"<([A-Za-z][A-Za-z0-9]*)\b[^>]*>(.*?)</\1>", RegexOptions.Singleline);
                    Match m = rgHtml.Match(s);
                    return m.Success ? m.Groups[2].Value.Trim(new char[] {'\r', '\n'}) : String.Empty;
                }
        }
        private void OK_Click(object sender, EventArgs e)
        {
            Value.InnerXml = rtbXML.Text.Replace("\n", String.Empty);
            Close();
        }
    }
}